package com.book.controller;

import com.book.pojo.User;
import com.book.service.UserService;
import com.book.utils.MsgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.*;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //验证用户名是否存在
    @PostMapping("/checkUserName")
    @ResponseBody
    public String checkUserName(String username) {
        return userService.checkUser(username);
    }

    //用户注册
    @PostMapping("/register")
    @ResponseBody
    public String register(User user, HttpSession session) {
        String username = user.getUsername();
        String flag = userService.checkUser(username);
        if ("102".equals(flag)) {
            return "102";
        }

        String sysCode = (String) session.getAttribute(user.getPhone());
        if (!user.getCode().equals(sysCode)) {
            return "103";
        }
        userService.save(user);  //保存用户
        return "success";
    }

    //用户登录  账号密码
    @PostMapping("/login")
    @ResponseBody
    public String toLogin(User user, HttpSession session, HttpServletResponse response) {
        return userService.loginCheck(user, session, response);
    }

    //用户登录  手机号
    @PostMapping("/phoneLogin")
    @ResponseBody
    public String toPhoneLogin(User user, HttpSession session, HttpServletResponse response) {
        return userService.phoneLoginCheck(user, session, response);
    }

    //用户退出
    @GetMapping("/logout")
    public String logOut(HttpSession session, HttpServletResponse response) {

        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);

        session.invalidate();
        return "redirect:/"; //重定向到首页
    }

    //获取验证码
    @PostMapping("/getCode")
    public void getCode(String phone, HttpSession session) {

        String str = "4396";
        //生成4位数的随机验证码
        //(int)((size + 1) * Math.random()) 构造随机数的范围 [0, size]
 /*   for(int i=0; i<4; i++){
        str += ((int)(Math.random() * 10));
    }

    //发送验证码
    MsgUtils.sendMsg(phone, str);
    */

        //保存验证码到 session
        session.setAttribute(phone, str);
        session.setMaxInactiveInterval(5 * 60);
    }
}
